// 医生数据
const doctorsByDepartment = {
	'内科': ['张建军', '李芳', '王宏伟', '周丽'],
	'外科': ['牛兆倬', '赵阳', '孙伟'],
	'儿科': ['陈雨'],
	'妇产科': ['吴芳'],
	'其他': ['刘敏']
};

const statusConfig = {
	booked: {
		text: '已预约',
		class: 'status-booked',
		canCancel: true
	},
	cancelled: {
		text: '已取消',
		class: 'status-cancelled',
		canCancel: false
	},
	completed: {
		text: '已完成',
		class: 'status-completed',
		canCancel: false
	}
};
document.addEventListener('DOMContentLoaded', function() {
	if (!Auth.isLoggedIn()) {
		alert('请先登录');
		window.location.href = 'login.html';
		return;
	}

	const userId = Auth.getCurrentUserId();
	if (!userId) return;



	// 初始化页面
	initDepartmentSelect();
	loadUserAppointments(userId);

	// 新建预约按钮事件
	document.getElementById('newAppointmentBtn').addEventListener('click', function() {
		document.getElementById('appointmentModal').style.display = 'block';
		// 初始化医生列表
		updateDoctorOptions();
	});

	// 关闭模态框
	document.querySelector('.close').addEventListener('click', function() {
		document.getElementById('appointmentModal').style.display = 'none';
	});

	// 表单提交事件
	document.getElementById('addAppointmentForm').addEventListener('submit', function(e) {
		e.preventDefault();
		addAppointment(userId);
	});

	// 科室选择变化事件
	document.getElementById('department').addEventListener('change', function() {
		updateDoctorOptions();
	});
});

// 获取当前用户ID
function getCurrentUserId() {
	// 实际应用中应从cookie或localStorage获取
	return localStorage.getItem('userId'); // 使用你的测试用户ID
}

// 初始化科室选择
function initDepartmentSelect() {
	const departmentSelect = document.getElementById('department');
	// 保留第一个选项（"请选择科室"）
	while (departmentSelect.options.length > 1) {
		departmentSelect.remove(1);
	}

	const departments = ['内科', '外科', '儿科', '妇产科', '其他'];
	departments.forEach(dept => {
		const option = document.createElement('option');
		option.value = dept;
		option.textContent = dept;
		departmentSelect.appendChild(option);
	});
}


function updateDoctorOptions() {
	const department = document.getElementById('department').value;
	const doctorSelect = document.getElementById('doctor');

	// 清空现有选项（保留第一个选项）
	while (doctorSelect.options.length > 1) {
		doctorSelect.remove(1);
	}

	if (department && doctorsByDepartment[department]) {
		doctorsByDepartment[department].forEach(doctor => {
			const option = document.createElement('option');
			option.value = doctor;
			option.textContent = doctor;
			doctorSelect.appendChild(option);
		});
	}
}

// 加载用户预约（适配后端格式）
function loadUserAppointments(userId) {
	fetch(`http://localhost:8080/api/appointments/${userId}`) // 注意URL修改为/user/{userId}
		.then(response => {
			if (!response.ok) throw new Error('网络响应不正常');
			return response.json();
		})
		.then(data => {
			if (data.code === 200) {
				renderAppointments(data.data); // 现在传入的是数组
			} else {
				throw new Error(data.message || '获取数据失败');
			}
		})
		.catch(error => {
			console.error('加载预约错误:', error);
			renderError(error.message);
		});
}

function renderAppointments(appointments) {
	const container = document.getElementById('appointmentsContainer');
	container.innerHTML = '';

	if (!appointments || appointments.length === 0) {
		container.innerHTML = '<p class="no-appointments">暂无预约记录</p>';
		return;
	}

	// 按预约日期倒序排序
	appointments.sort((a, b) => new Date(b.date) - new Date(a.date));

	appointments.forEach(appointment => {
		// 获取状态配置
		const status = statusConfig[appointment.status] || {
			text: '未知状态',
			class: 'status-unknown',
			canCancel: false
		};

		// 身份证脱敏处理
		const maskedIdCard = appointment.idCard ?
			appointment.idCard.substring(0, 3) + '​**​**' + appointment.idCard.substring(appointment.idCard
				.length - 4) :
			'未提供';

		const card = document.createElement('div');
		card.className = 'appointment-card';
		card.dataset.id = appointment.id;

		card.innerHTML = `
            <div class="appointment-header">
                <div class="appointment-name">${appointment.username || '未命名'}</div>
                <div class="appointment-status ${status.class}">${status.text}</div>
            </div>
            <div class="appointment-details">
                <div class="appointment-detail">
                    <strong>身份证号</strong>
                    ${maskedIdCard}
                </div>
                <div class="appointment-detail">
                    <strong>预约时间</strong>
                    ${appointment.date} ${appointment.time || ''}
                </div>
                <div class="appointment-detail">
                    <strong>科室</strong>
                    ${appointment.department || '未指定'}
                </div>
                <div class="appointment-detail">
                    <strong>医生</strong>
                    ${appointment.doctorName || '未指定'}
                </div>
            </div>
            <div class="appointment-actions">
                ${status.canCancel ? `
                <button class="action-btn cancel-btn" data-id="${appointment.id}">
                    <i class="fas fa-times"></i> 取消预约
                </button>
                ` : ''}
            </div>
        `;

		container.appendChild(card);
	});

	// 绑定所有取消按钮事件
	document.querySelectorAll('.cancel-btn').forEach(btn => {
		btn.addEventListener('click', function() {
			cancelAppointment(this.dataset.id);
		});
	});
}

// 显示错误信息
function renderError(message) {
	const container = document.getElementById('appointmentsContainer');
	container.innerHTML = `
        <div class="error-message">
            <i class="fas fa-exclamation-triangle"></i>
            ${message || '加载预约记录失败'}
        </div>
    `;
}

// 添加预约（适配后端格式）
function addAppointment(userId) {
	const form = document.getElementById('addAppointmentForm');
	const formData = new FormData(form);

	// 构建符合后端要求的数据结构
	const appointmentData = {
		username: formData.get('username'),
		idCard: formData.get('idCard'),
		department: formData.get('department'),
		date: formData.get('date'),
		time: formData.get('time'),
		doctorName: formData.get('doctorName'),
		userId: userId,
		status: 'booked' // 默认状态
	};

	fetch('http://localhost:8080/api/appointments', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
			},
			body: JSON.stringify(appointmentData)
		})
		.then(response => {
			if (!response.ok) throw new Error('网络响应不正常');
			return response.json();
		})
		.then(data => {
			if (data.code === 200) {
				alert('预约成功！');
				form.reset();
				document.getElementById('appointmentModal').style.display = 'none';
				loadUserAppointments(userId);
			} else {
				throw new Error(data.message || '预约失败');
			}
		})
		.catch(error => {
			console.error('添加预约错误:', error);
			alert('添加预约失败: ' + error.message);
		});
}

// 取消预约（适配后端格式）
function cancelAppointment(id) {
	// 1. 直接从DOM获取当前预约卡片
	const card = document.querySelector(`.appointment-card[data-id="${id}"]`);
	if (!card) {
		alert('未找到预约信息');
		return;
	}

	// 2. 从卡片中提取关键信息
	const statusElement = card.querySelector('.appointment-status');
	const statusText = statusElement?.textContent.trim() || '';

	// 3. 检查状态是否允许取消（直接使用页面显示的状态文本）
	if (statusText !== '已预约') {
		alert(`只有【待处理】状态可取消，当前状态【${statusText}】`);
		return;
	}

	// 4. 获取其他需要的信息（用于确认提示）
	const departmentElement = card.querySelector('.appointment-detail:nth-child(3)');
	const department = departmentElement ?
		departmentElement.textContent.replace('科室', '').trim() : '';

	const doctorElement = card.querySelector('.appointment-detail:nth-child(4)');
	const doctor = doctorElement ?
		doctorElement.textContent.replace('医生', '').trim() : '';

	// 5. 确认提示
	if (!confirm(`确定要取消${department ? `【${department}】` : ''}${doctor ? ` ${doctor}医生` : ''}的预约吗？`)) {
		return;
	}

	// 6. 显示加载状态
	const btn = card.querySelector('.cancel-btn');
	const originalText = btn.innerHTML;
	btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 取消中...';
	btn.disabled = true;

	// 7. 发送取消请求
	fetch(`http://localhost:8080/api/appointments/${id}/cancel`, {
			method: 'PUT',
			headers: {
				'Content-Type': 'application/json'
			}
		})
		.then(response => {
			if (!response.ok) throw new Error('网络响应不正常');
			return response.json();
		})
		.then(data => {
			if (data.code === 200) {
				alert('预约已取消');
				// 刷新列表
				loadUserAppointments(getCurrentUserId());
			} else {
				throw new Error(data.message || '取消预约失败');
			}
		})
		.catch(error => {
			console.error('取消预约错误:', error);
			alert('取消预约失败: ' + error.message);
		})
		.finally(() => {
			// 恢复按钮状态
			if (btn) {
				btn.innerHTML = originalText;
				btn.disabled = false;
			}
		});
}

// 点击模态框外部关闭
window.addEventListener('click', function(event) {
	const modal = document.getElementById('appointmentModal');
	if (event.target === modal) {
		modal.style.display = 'none';
	}
});